<template>
	<view class="px-2 py-4">
		<wd-message-box />
		<wd-toast />
		<form-component :formFields="formFields" :formData="formData" :formRules="formRules" :fileLists="fileLists"
			:startUserSelectTasks="startUserSelectTasks" :startUserSelectAssignees="startUserSelectAssignees"
			:startUserSelectAssigneesFormRules="startUserSelectAssigneesFormRules" :detailId="detailId"
			:resubmit="resubmit" @submitForm="submitForm" @cancelForm="cancelForm" />
	</view>
</template>

<script setup lang="ts">
import {
	onLoad
} from "@dcloudio/uni-app";
import { ref, reactive, nextTick, computed } from 'vue'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { buildFileList } from '@/utils/fileUtils'
import { getAccessToken } from '@/utils/auth'
import * as DefinitionApi from '@/api/bpm/definition'
import { getUserProfile } from "@/api/system/user/profile";
import { ApprovalrequestreportApi, ApprovalrequestreportVO } from '@/api/oa/Approvalrequestreport'
import { useMessage, useToast } from 'wot-design-uni'
import { formatDate, parseDateToTimestamp } from '@/utils/formatTime'


const message = useMessage()
const toast = useToast()
const globalConfig = (getApp() as any).globalData.config;
const detailId = ref(null)
const resubmit = ref(0)
const headerObj = ref(
	{
		Authorization: 'Bearer ' + getAccessToken()
	}
)

// 指定审批人
const processDefineKey = 'oa_internal_report' // 流程定义 Key
const startUserSelectTasks = ref<any>([]) // 发起人需要选择审批人的用户任务列表
const startUserSelectAssignees = ref<any>({}) // 发起人选择审批人的数据
const startUserSelectAssigneesFormRef = ref() // 发起人选择审批人的表单 Ref
const startUserSelectAssigneesFormRules = ref<any>({}) // 发起人选择审批人的表单 Rules
const userList = ref<any[]>([]) // 用户列表
const depList = ref<any[]>([]) // 部门列表
const sealList = ref<any[]>([])
const userProfile = ref<any>({})

// 独立文件存储（按字段名存储）
const fileLists = ref<Record<string, any[]>>({
	url: []
})
//表单项字段配置
const formFields = ref<any[]>([
	{
		type: 'input',
		prop: 'title',
		label: '标题',
		placeholder: '请输入标题'
	},
	{
		type: 'input',
		prop: 'serialNumber',
		label: '台账序号',
		placeholder: '请输入台账序号'
	},
	{
		type: 'input',
		prop: 'userName',
		label: '发起人',
		placeholder: '请输入发起人',
		readonly: true
	},
	{
		type: 'input',
		prop: 'deptName',
		label: '发起人部门',
		placeholder: '发起人部门',
		readonly: true
	},
	{
		type: 'datetime',
		prop: 'initiationDate',
		label: '发起日期',
		placeholder: '选择日期',
		datetimeType: 'date',
	},
	{
		type: 'input',
		prop: 'summary',
		label: '事由简述',
		placeholder: '请输入事由简述'
	},
	{
		type: 'upload',
		prop: 'url',
		label: '附件',
		placeholder: '上传附件',
		action: globalConfig.uploadUrl,
		limit: 1,
		accept: 'all',
		drag: true,
		header: headerObj.value,   // 如果有 token 或 header，你自己确认 headerObj.value 是否需要
		targetMapping: {
			fileUrl: 'url',
			fileName: 'ename'
		},
	},
	{
		type: 'input',
		prop: 'remark',
		label: '备注',
		placeholder: '请输入备注'
	}
])
const formData = ref<ApprovalrequestreportVO>({
} as any)
const formRules = reactive({
	title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
	userName: [{ required: true, message: '请输入发起人', trigger: 'blur' }],
	deptName: [{ required: true, message: '请选择发起人部门', trigger: 'change' }],
	initiationDate: [{ required: true, message: '请选择发起日期', trigger: 'change' }],
	summary: [{ required: true, message: '请输入事由简述', trigger: 'blur' }],
	url: [{ required: true, message: '请上传正文', trigger: 'change' }]
})


onLoad(async (options) => {
	const processDefinitionDetail = await DefinitionApi.getProcessDefinition(
		undefined,
		processDefineKey
	)
	if (!processDefinitionDetail) {
		toast.error('流程模型未配置，请检查！')
		return
	}
	startUserSelectTasks.value = processDefinitionDetail.startUserSelectTasks
	// 设置指定审批人
	if (startUserSelectTasks.value?.length > 0) {
		// 设置校验规则
		for (const userTask of startUserSelectTasks.value) {
			startUserSelectAssignees.value[userTask.id] = []
			startUserSelectAssigneesFormRules.value[userTask.id] = [
				{

					required: true,
					message: '请选择审批人',
					validator: (value: any) => {
						if (value && Array.isArray(value) && value.length > 0) {
							return Promise.resolve();
						} else {
							return Promise.reject('审批人不能为空');
						}
					},
					trigger: ['change']

				}
			]
		}
		// console.log('startUserSelectAssignees.value', startUserSelectAssignees.value);
		// console.log('startUserSelectAssigneesFormRules.value', startUserSelectAssigneesFormRules.value);
	}
	detailId.value = options?.id
	resubmit.value = options?.resubmit
	/** 获得详情 */
	if (detailId.value) { getDetailById() }


	getUserInfo()

})


/** 获取页面详情 */
const getDetailById = async () => {
	try {
		const data = await ApprovalrequestreportApi.getApprovalrequestreport(Number(detailId.value))
		formData.value = data
		if (formData.value.initiationDate) {
			formData.value.initiationDate = parseDateToTimestamp(formData.value.initiationDate)
		}
		// 附件字段回显
		fileLists.value.url = buildFileList(data.url) as any;
		console.log('formData.value', formData.value);
	} catch (error) {
		console.log('加载数据失败')
	}
}
/**获取用户信息**/
const getUserInfo = async () => {
	userProfile.value = await getUserProfile()
	if (userProfile.value) {
		formData.value.userId = userProfile.value.id
		formData.value.userName = userProfile.value.nickname
		formData.value.deptId = userProfile.value.dept.id
		formData.value.deptName = userProfile.value.dept.name
	}
}

/** 提交表单 */
const submitForm = async (payload: any) => {
	const { type, data } = payload
	try {
		if (type === 'update') {
			await ApprovalrequestreportApi.updateApprovalrequestreport(data)
			toast.success('编辑成功');
		} else {
			await ApprovalrequestreportApi.createApprovalrequestreport(data)
			toast.success('新增成功');
		}
		// 成功后跳转
		uni.navigateTo({ url: '/pagesPackage/OAsystemAutomation/Approvalrequestreport/index' });
	} catch (error) {
		console.error('表单提交失败:', error);
		toast.error('提交失败，请稍后再试');
	}
}

/** 取消表单 */
const cancelForm = async () => {
	try {
		// 删除的二次确认
		await message.confirm({
			msg: '您确定要取消吗？',
			title: '提示'  // 添加标题
		})
		uni.navigateTo({ url: '/pagesPackage/OAsystemAutomation/Approvalrequestreport/index' });
		// 显示成功提示
		toast.success('取消成功')
	} catch (error) {
		console.log('用户取消了操作或发生错误:', error)
	}
}
</script>

<style scoped lang="scss">
.container {
	padding: 20px 5px;
}

.custom-shadow {
	width: 40%;
	border-radius: 5%;
}
</style>